/**
 * Created by leamiko on 2017/1/1.
 */

!function(window, $, miju) {

    // function KeyBoard (element, options) {
    //     this.$element = $(element);
    //     this.options = $.extend({}, KeyBoard.DEFAULTS, options || {});
    //     this.init();
    // }
    // KeyBoard.DEFAULTS = {
    //     disorder: false,
    //     title: '安全键盘'vszy
    // };
    //
    // KeyBoard.prototype.init = function () {};
    //
    // KeyBoard.prototype.open = function () {};
    //
    // KeyBoard.prototype.close = function () {};
    //
    // KeyBoard.prototype.bindEvent = function () {};
    //
    // KeyBoard.prototype.unbindEvent = function () {};
    //
    // KeyBoard.prototype.fillPassword = function () {};
    //
    // KeyBoard.prototype.clearError = function () {};
    //
    // KeyBoard.prototype.error = function (mes) {};
    //
    // KeyBoard.prototype.backspace = function () {};
    //
    // KeyBoard.prototype.createNumsHtml = function () {};
    //
    // KeyBoard.prototype.createNums = function () {};
    //
    // KeyBoard.prototype.upsetOrder = function (arr) {};

    var DATA_KEY_KEYBOARD = 'miju.keyboard';

    var $body = $(window.document.body),
        isMobile = !!(window.navigator && window.navigator.userAgent || '').match(/AppleWebKit.*Mobile.*/) || 'ontouchstart' in window.document.documentElement,
        triggerEvent = isMobile ? 'touchstart' : 'click';

    var KeyBoard = miju.Class.extend({

        init: function(element, options) {
            this.$element = $(element);
            this.options = $.extend({}, KeyBoard.DEFAULTS, options || {});
            this.initView();
        },

        initView: function() {
            var self = this;
            // self.$mask = $('<div class="mask-black"></div>');

            var _this = this;

            _this.inputNums = '';

            _this.toggleClass = 'keyboard-show';

            function getDot () {
                var s = '';
                for (var i = 0; i < 6; i++) {
                    s += '<li><i></i></li>';
                }
                return s;
            }

            if (!_this.options.placeholder) { // 对话框中现实输入控件
                _this.showKeyword = true;
            }

            var hd = '';
            if (_this.showKeyword) {
                hd = hd + '<div class="keyboard-head"><strong>输入数字密码</strong></div>';
                // '<div class="keyboard-error">请输入正确的支付密码</div>' +
            }

            hd = hd +
                '<div class="keyboard-password-wrap"><ul class="m-keyboard-password keyboard-password J_FillPwdBox">' + getDot() + '</ul></div>';
                ;

            var ft = '' +
                '<div class="keyboard-content">' +
                '   <div class="keyboard-title">' + _this.options.title + '</div>' +
                '   <ul class="keyboard-numbers"></ul>' +
                '</div>';

            _this.$element.prepend(hd).append(ft);

            if (!_this.showKeyword) {
                _this.$element.find('.keyboard-password-wrap').hide();
            }

            _this.$numsBox = _this.$element.find('.keyboard-numbers');

            _this.$mask = $('<div class="mask-black"></div>');

            if (!_this.showKeyword) { // 移除
                _this.keyboardPwd = _this.$element.find('.keyboard-password').detach();
                _this.options.placeholder && _this.options.placeholder.append(_this.keyboardPwd);
            }

        },

        open: function() {
            var self = this;
            var _this = this,
                $element = _this.$element,
                $numsBox = _this.$numsBox;

            $element.addClass(_this.toggleClass);

            if (_this.options.disorder || $numsBox.data('loaded-nums') != 1) {
                $numsBox.data('loaded-nums', 1).html(_this.createNumsHtml());
            }

            _this.showKeyword && $body.append(_this.$mask);

            _this._bindEvent();
        },

        close: function() {
            var self = this;
            var _this = this;

            !_this.options.placeholder && _this.$mask.remove();
            _this.$element.removeClass(_this.toggleClass);
            _this._unbindEvent();

            _this.inputNums = '';
            _this._fillPassword();

            // _this.clearError();
        },

        _bindEvent: function() {
            var _this = this,
                $element = _this.$element;

            _this.$mask.on(triggerEvent + '.miju.keyboard.mask', function (e) {
                e.preventDefault();
                _this.close();
            });

            $element.on(triggerEvent + '.miju.keyboard.nums', '.J_Nums', function (e) {
                if (_this.inputNums.length >= 6)return;

                _this.inputNums = _this.inputNums + $(this).html();

                // _this.clearError();
                _this._fillPassword();
            });

            // 退格
            $element.on(triggerEvent + '.miju.keyboard.backspace', '.J_Backspace', function (e) {
                e.preventDefault();
                _this._backspace();
            });

            // 取消
            $element.on(triggerEvent + '.miju.keyboard.cancel', '.J_Cancel', function (e) {
                e.preventDefault();
                _this.close();
            });
        },

        _unbindEvent: function() {
            this.$element.off(triggerEvent + '.miju.keyboard');
        },

        /**
         * 填充密码
         */
        _fillPassword: function () {
            var _this = this,
                inputNums = _this.inputNums,
                length = inputNums.length;

            var $keyboardPwd = _this.keyboardPwd || _this.$element.find('.J_FillPwdBox');

            var $li = $keyboardPwd.find('li');
            $li.find('i').hide();

            $li.each(function(i, element) {
                if (i < length) {
                    $(element).find('i').css('display', 'block');
                }
            });
            // $li.filter(':lt(' + length + ')').find('i').css('display', 'block');

            if (length >= 6) {
                // _this.$element.trigger($.Event('done.miju.keyboard', {
                //     password: inputNums
                // }));

                _this.options.ondonekeyboard && _this.options.ondonekeyboard({
                    password: inputNums
                });
            }
        },

        _backspace: function () {
            var _this = this;

            var _inputNums = _this.inputNums;
            if (_inputNums) {
                _this.inputNums = _inputNums.substr(0, _inputNums.length - 1);
            }

            _this._fillPassword();
        },

        /**
         * 创建键盘HTML
         * @returns {string}
         */
        createNumsHtml: function () {
            var _this = this,
                nums = _this.createNums();

            _this.options.disorder && _this.upsetOrder(nums);

            var arr = [];
            $.each(nums, function (k) {
                if (k % 3 == 0) {
                    if (k >= nums.length - 2) {
                        arr.push('<li><a href="javascript:;" class="J_Cancel">取消</a>' + nums.slice(k, k + 3).join('') + '<a href="javascript:;" class="J_Backspace"></a></li>');
                    } else {
                        arr.push('<li>' + nums.slice(k, k + 3).join('') + '</li>');
                    }
                }
            });

            return arr.join('');
        },

        /**
         * 创建键盘数字
         * @returns {Array} DOM数组
         */
        createNums: function () {
            var _this = this;
            var disorder = _this.options.disorder;

            if (disorder && _this.cacheNums) {
                return _this.cacheNums;
            }

            var strArr = [];
            for (var i = 1; i <= 10; i++) {
                strArr.push('<a href="javascript:;" class="J_Nums">' + (i % 10) + '</div>');
            }

            if (!disorder) {
                _this.cacheNums = strArr;
            }

            return strArr;
        },

        /**
         * 打乱数组顺序
         * @param arr 数组
         * @returns {*}
         */
        upsetOrder: function (arr) {
            var floor = Math.floor,
                random = Math.random,
                len = arr.length, i, j, temp,
                n = floor(len / 2) + 1;
            while (n--) {
                i = floor(random() * len);
                j = floor(random() * len);
                if (i !== j) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
            return arr;
        }
    });

    KeyBoard.DEFAULTS = {
        disorder: false,
        title: '安全键盘',
        ondonekeyboard: function(ret) {
            console.log('输入的密码是：' + ret.password);
        }
    };

    // Zepto插件  TODO 无效?
    // function Plugin(option) {
    //     var args = Array.prototype.slice.call(arguments, 1);
    //
    //     return this.each(function () {
    //
    //         var $this = $(this),
    //             keyboard = $this.data(DATA_KEY_KEYBOARD);
    //
    //         if (!keyboard) {
    //             $this.data(DATA_KEY_KEYBOARD, (keyboard = new KeyBoard(this, option)));
    //         }
    //
    //         if (typeof option == 'string') {
    //             console.log(option);
    //             console.log(KeyBoard);
    //             keyboard[option] && keyboard[option].apply(keyboard, args);
    //         }
    //
    //         // return $this;
    //     });
    // }

    // miju Plugin
    function Plugin(options) {
        //遍历选择的元素
        this.each(function(i, element) {
            if (element.keyboard) return;
            if (options) {
                element.keyboard = new KeyBoard(element, options);
            } else {
                var optionsText = element.getAttribute('data-keyboard-options');
                var _options = optionsText ? JSON.parse(optionsText) : {};
                element.keyboard = new KeyBoard(element, _options);
            }
        });
        return this[0] ? this[0].keyboard : null;
    }

    miju.fn.keyBoard = Plugin;

}(window, Zepto, miju);
